<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 警告 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 表单选择商品 -->
      <el-form ref="selectGoods" label-width="100px">
        <el-form-item label="选择商品分类:">
          <el-cascader
            v-model="selectKeys"
            :options="selectCascader"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="selectHandleChange"
          ></el-cascader>
        </el-form-item>
      </el-form>

      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClickTags">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            :disabled="isBtnDisabled"
            type="primary"
            size="small"
            @click="showDialog"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 标签 -->
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="closeTagName(scope.row, i)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input
                  class="tagInput"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputTagValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else size="small" @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            :disabled="isBtnDisabled"
            type="primary"
            size="small"
            @click="showDialog"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 标签 -->
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="closeTagName(scope.row, i)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input
                  class="tagInput"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputTagValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else size="small" @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数和静态属性弹出框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closeAddDialog"
    >
      <!-- 添加参数或属性的表单 -->
      <el-form
        :model="addRuleForm"
        :rules="addRules"
        ref="addRuleFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureAddData">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改编辑动态参数和静态属性弹出框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editAddDialog"
    >
      <!-- 添加参数或属性的表单 -->
      <el-form
        :model="editRuleForm"
        :rules="editRules"
        ref="editRuleFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 级联选择器的数据
      selectCascader: [],
      // 级联选择的结果
      selectKeys: [],
      // 被激活的页签的名称
      activeName: "many",
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 弹出框是否展示
      addDialogVisible: false,
      // 弹出框里面的表单数据
      addRuleForm: {
        attr_name: "",
      },
      // 弹出框里面的表单数据的校验规则
      addRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      // 编辑弹出框是否展示
      editDialogVisible: false,
      // 编辑弹出框的表单数据
      editRuleForm: {},
      // 编辑弹出框的表单数据的校验规则
      editRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    // 如果按钮需要被禁用，则返回true，否则返回false
    isBtnDisabled() {
      if (this.selectKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 当前选中的三级分类的ID
    cateId() {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2];
      }
      return null;
    },
    // 静态属性或者动态参数
    titleText() {
      if (this.activeName === "many") return "动态参数";
      if (this.activeName === "only") return "静态属性";
    },
  },

  methods: {
    // 获取商品分类数据列表  供级联选择器
    async getCategoriesTypeTwo() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("请求级联数据失败");
      }
      this.selectCascader = res.data;
      // console.log(this.selectCascader);
    },
    // 级联选择框改变触发这个函数
    selectHandleChange() {
      this.getParamsData();
    },
    // 更换标签页触发这个函数
    handleClickTags(tab, event) {
      // console.log(tab,event)
      console.log(this.activeName);
      this.getParamsData();
    },
    async getParamsData() {
      // 证明选择的不是三级分类
      if (this.selectKeys.length !== 3) {
        this.selectKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      console.log(this.selectKeys);
      // 根据所选分类的ID，和当前所处的面板，获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );
      if (res.meta.status !== 200) return this.$message.error("获取参数失败");
      console.log(res.data);
      // 将里面的attr_vals切割成数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制文本框的显示与隐藏
        item.inputVisible = false;
        // 文本框中输入的值
        item.inputTagValue = "";
      });

      // 判断一下获取的数据是many还是only,再将数据指定存储
      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    // 点击添加弹出对话框
    showDialog() {
      this.addDialogVisible = true;
    },
    // 退出对话框触发这个函数
    closeAddDialog() {
      // 关闭之后清空校验规则
      this.$refs.addRuleFormRef.resetFields();
    },
    // 对话框点击确定触发这个函数
    sureAddData() {
      this.$refs.addRuleFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addRuleForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加参数失败！");
        }
        this.$message.success("添加参数成功");
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    // 点击按钮修改参数或属性
    async showEditDialog(id) {
      // 查询当前参数的信息
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("获取参数信息失败");
      }
      this.editRuleForm = res.data;
      this.editDialogVisible = true;
      // console.log(id)
    },
    // 修改弹出框关闭触发这个函数
    editAddDialog() {
      // 关闭之后清空校验规则
      this.$refs.editRuleFormRef.resetFields();
    },
    // 修改弹出框确定之后触发这个函数
    editParams() {
      this.$refs.editRuleFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editRuleForm.attr_id}`,
          { attr_name: this.editRuleForm.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改参数失败");
        }
        this.$message.success("修改数据成功!");
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },
    // 根据id删除对对应的参数项
    removeParams(id) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 删除的业务逻辑
          const data = await this.$http.delete(
            `categories/${this.cateId}/attributes/${id}`
          );
          console.log(data);
          this.getParamsData();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 展示标签taginput框
    showInput(row) {
      row.inputVisible = true;
      // 让文本框自动获得焦点
      // $nextTick方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 标签input框按下回车和失去焦点之后之后触发这个函数
    async handleInputConfirm(row) {
      if (row.inputTagValue.trim().length === 0) {
        row.inputTagValue = "";
        row.inputVisible = false;
        return;
      }
      // 如果没有return出去，说明输入内容合法，进行后续操作
      row.attr_vals.push(row.inputTagValue.trim());
      row.inputTagValue = "";
      row.inputVisible = false;
      // 添加了参数，更新数据库里面的信息，（发请求）
      this.handleRowAttr_vals(row, "添加标签失败！");
    },
    // 关闭标签删除标签
    closeTagName(row, i) {
      // attr_vals第i个开始，删除一个数据，并且改变原数组
      // 在这里这行代码比过滤效率高
      row.attr_vals.splice(i, 1);

      // row.attr_vals = row.attr_vals.filter((item, index, array) => {
      //   return index !== i;
      // });
      this.handleRowAttr_vals(row, "删除标签失败！");
    },
    // 添加或删除参数标签的请求
    async handleRowAttr_vals(row, msg = "更新数据失败") {
      let newAttr_vals = row.attr_vals.join(" ");
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: newAttr_vals,
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error(msg);
      }
    },
  },
  mounted() {
    this.getCategoriesTypeTwo();
  },
};
</script>

<style scoped lang="less">
.el-form {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.tagInput {
  width: 100px;
}
</style>